package proxynew;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import net.jxta.exception.PeerGroupException;
import net.jxta.platform.NetworkManager;

public class ProxyMain {
	
	private static List<String> getMulticastGroups() throws IOException {
		List<String> groups = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("groups.txt")));
		String strLine;
	    while ((strLine = reader.readLine()) != null)   {
	    	groups.add(strLine);
	      }
		//groups.add("224.5.5.1:27000");		
		return groups;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		List<Thread> sniffers = new ArrayList<Thread>();
		NetworkManager networkManager = null;
		try {
			networkManager = startJxta();
		} catch (Exception e) {
			System.err.println("ProxyMain: Error connecting to overlay");
			e.printStackTrace();
			return;
		}
		
		DiscoveryListener discListener = new DiscoveryListener(networkManager);
		discListener.start();
		
		PipeMsgListener pipeListener = new PipeMsgListener(networkManager);
		pipeListener.start();

		try {
			for (String group : ProxyMain.getMulticastGroups()) {
				
				MulticastSniffer ms = new MulticastSniffer(group, networkManager);
				ms.start();
				sniffers.add(ms);			
			}
		} catch (IOException e) {
			e.printStackTrace();
			networkManager.stopNetwork();
		}	
		
		wait_thread(discListener);
		wait_thread(pipeListener);
				
		for (Thread threadSniffer : sniffers) {
			wait_thread(threadSniffer);
		}
	}

	private static void wait_thread(Thread t1) {
		try {
			t1.join();
		} catch (InterruptedException e) {
			System.err.println("ProxyMain: Exception waiting for thread.");
		}
	}

	private static NetworkManager startJxta() throws IOException, PeerGroupException {
        NetworkManager manager = null;

        manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "ProxyMain", new File(new File(".cache"), "ProxyMain").toURI());
        System.out.println("ProxyMain: Starting JXTA");
        manager.startNetwork();
        System.out.println("ProxyMain: JXTA Started");
        
        return manager;
	}

}
